/**
 * @description Receive data stream to generate blob, create link, download file
 * @param {Function} api API method to export table (required)
 * @param {String} tempName Exported file name (required)
 * @param {Object} params Exported parameters (default {})
 * @param {String} fileType Exported file format (default is .xlsx)
 * */

import { FileLink } from '@/api/modules';

function getFileFormat(fileStream) {
  const byteArray = new Uint8Array(fileStream).subarray(0, 8); // 读取文件流的前8个字节
  const hexArray = Array.from(byteArray, (byte) =>
    byte.toString(16).toUpperCase().padStart(2, '0')
  ); // 转换为十六进制数组
  const fileHeader = hexArray.join(' '); // 将十六进制数组转换为字符串

  if (fileHeader === 'FF D8') {
    return 'JPEG';
  } else if (fileHeader === '89 50 4E 47 0D 0A 1A 0A') {
    return 'PNG';
  } else if (fileHeader.startsWith('47 49 46 38')) {
    return 'GIF';
  } else if (fileHeader.startsWith('25 50 44 46 2D')) {
    return 'PDF';
  } else if (fileHeader === 'D0 CF 11 E0 A1 B1 1A E1') {
    return 'DOC';
  } else if (fileHeader === '50 4B 03 04') {
    const subArray = new Uint8Array(fileStream).subarray(30, 34);
    const hexSubArray = Array.from(subArray, (byte) =>
      byte.toString(16).toUpperCase().padStart(2, '0')
    );
    const subFileType = hexSubArray.join(' ');
    if (subFileType === 'EC A5 C1 00' || subFileType === '0E 10') {
      return 'XLS';
    } else if (subFileType === 'FD FF 4B 00') {
      return 'PPT';
    } else {
      return 'Unknown';
    }
  } else if (
    fileHeader === '50 4B 05 06' ||
    fileHeader === '50 4B 07 08' ||
    fileHeader === '50 4B 4C 49 54 45'
  ) {
    return 'DOCX'; // .docx, .xlsx and .pptx
  }

  return 'Unknown'; // 未知格式
}

export const useDownload = async (
  api: (param: any) => Promise<any>,
  tempName: string,
  lang = 'ar',
  exportType = 2,
  fileType = '.xlsx',
  params: any = {}
) => {
  try {
    const res = await api({ ...params, lang, exportType });
    const blob = new Blob([res]);
    if ('msSaveOrOpenBlob' in navigator)
      return window.navigator.msSaveOrOpenBlob(blob, tempName + fileType);
    const blobUrl = window.URL.createObjectURL(blob);
    const exportFile = document.createElement('a');
    exportFile.style.display = 'none';
    exportFile.download = `${tempName}${fileType}`;
    exportFile.href = blobUrl;
    document.body.appendChild(exportFile);
    exportFile.click();
    document.body.removeChild(exportFile);
    window.URL.revokeObjectURL(blobUrl);
  } catch (error) {
    console.log(error);
  }
};

function validateLink(url) {
  const pattern = /(ht|f)tp(s?):\/\/[0-9a-zA-Z]?/;
  return pattern.test(url);
}

function getFileName(url) {
  const pattern = /\/([^/?]+)(\?.*)?$/;
  const match = url.match(pattern);
  if (match) {
    return match[1];
  }
  return null;
}

export const showDoc = async (url) => {
  let fileLink = url;
  if (!validateLink(url)) {
    const { data } = await FileLink({ objectKey: url, fileName: '' }, true);
    fileLink = data;
  }
  window.open(fileLink, '_blank');
};

export const usedownloadDoc = async (url: string, fileName = '') => {
  let fileLink = url;
  let name = fileName || url;
  if (!fileName) {
    name = getFileName(fileLink);
  }
  //判断是不是http
  if (!validateLink(url)) {
    const { data } = await FileLink({ objectKey: url, fileName: name }, true);
    fileLink = data;
  }

  console.log(name);
  const eleLink = document.createElement('a');
  eleLink.href = fileLink;
  eleLink.download = name; //下载后文件名
  eleLink.style.display = 'none';
  // 触发点击
  document.body.appendChild(eleLink);
  eleLink.click(); //点击下载
  //下载完成移除元素
  document.body.removeChild(eleLink);

  // fetch(fileLink, {
  //   method: 'GET',
  // })
  //   .then((response) => response.blob())
  //   .then((myBlob) => {
  //     const eleLink = document.createElement('a');
  //     let href = '';
  //     if (typeof myBlob == 'string') {
  //       eleLink.target = '_blank';
  //     } else {
  //       href = window.URL.createObjectURL(myBlob); //创建下载的链接
  //     }
  //     eleLink.href = href;
  //     eleLink.download = name; //下载后文件名
  //     eleLink.style.display = 'none';
  //     // 触发点击
  //     document.body.appendChild(eleLink);
  //     eleLink.click(); //点击下载
  //     //下载完成移除元素
  //     document.body.removeChild(eleLink);
  //     if (typeof myBlob == 'string') {
  //       window.URL.revokeObjectURL(href); //释放掉blob对象
  //     }
  //   })
  //   .catch((e) => {
  //     console.log(e);
  //   });
};
